// 继承了我们在最开始实现的抽象类RequstInterceptors，主要关心responseInterceptorsCatch内容
import Request from '@/api/axios'
import axios, { HttpStatusCode, type AxiosError } from 'axios'
import { message } from 'ant-design-vue'
import { checkErrorStatus } from '@/api/axios/checkErrorStatus'
import type { RequestInterceptors } from '@/api/axios/type'
import { useLocalStorage } from '@vueuse/core'
const AccessToken = useLocalStorage('access_token', null)
const RefreshToken = useLocalStorage('refresh_token', null)
const userName = useLocalStorage('userName', null)
const password = useLocalStorage('password', null)
export const _RequstInterceptors: RequestInterceptors = {
    requestInterceptors(config) {
        config.headers['Authorization'] ||= AccessToken.value
        return config
    },
    requestInterceptorsCatch(err) {
        return err
    },
    responseInterceptors(res) {
        process.env.NODE_ENV !== 'production' &&
            process.env.NODE_ENV !== 'production' &&
            console.log(res.data)
        if (res.data.code === HttpStatusCode.Unauthorized && RefreshToken.value) {
            return refreshToken()
                .then(async () => {
                    const newConfig = {
                        ...res.config,
                        headers: {
                            ...res.config.headers,
                            Authorization: `${AccessToken.value}`
                        }
                    }
                    return await Request.request(newConfig)
                })
                .catch((error) => {
                    console.error('Failed to retry request after refreshing token:', error)
                    return res
                })
        }
        return res
    },
    responseInterceptorsCatch(axiosInstance, err: AxiosError) {
        const message = err.code === 'ECONNABORTED' ? '请求超时' : undefined
        process.env.NODE_ENV !== 'production' &&
            process.env.NODE_ENV !== 'production' &&
            console.log('catch', err)
        if (axios.isCancel(err)) {
            return Promise.reject(err)
        }
        checkErrorStatus(
            (err as AxiosError).response?.status,
            message,
            (message) =>
                process.env.NODE_ENV !== 'production' &&
                process.env.NODE_ENV !== 'production' &&
                console.log(message)
        )
        // return retry(axiosInstance, err as AxiosError)
    }
}

const refreshToken = () => {
    return Request.post({
        url: '/user/refresh',
        data: {
            username: userName.value,
            password: password.value
        },
        headers: {
            Authorization: RefreshToken.value
        }
    })
        .then((response) => {
            if (response.code == HttpStatusCode.Ok) {
                ;[AccessToken.value, RefreshToken.value] = [response.info[0], response.info[1]]
                return true
            } else {
                ;[AccessToken.value, RefreshToken.value] = [null, null]
                message.error('请重新登录')
                return false
            }
        })
        .catch((err) => {
            process.env.NODE_ENV !== 'production' &&
                process.env.NODE_ENV !== 'production' &&
                console.log(err)
            return false
        })
}
